/*global require*/
'use strict';

//根视图
var rootView;
//注册插件
require.config({    
    paths: {
    	text:'js/requirejs-text/text',
        jquery: 'js/jquery-1.12.3',
        jsonParse:'js/jquery.json',
        httphelp:'service/httphelp',
        backbone: 'js/backbone-min',
        underscore: 'js/underscore-min',
        bootstrap:'bootstrap-3.3.5-dist/js/bootstrap',
        localStorage:'js/backbone.localStorage',
        backboneQuery:'js/backbone-query',
        "backbone-query-parameters":'js/backbone.queryparams',
        validation:'js/backbone-validation', 
        "backbone.paginator":'js/backbone.paginator',
        backgrid:'js/backgrid',
        "backgrid-paginator":'js/backgrid-paginator',
        'backgrid-mypaginator':'js/backgrid-mypaginator',
        'backgrid-button-cell':'js/backgrid-button-cell',
        'bootstrap-paginator': 'js/bootstrap-paginator',
        modules: 'modules',
        model: 'model',
        data:'data',
        personnelView:'modules/personnel/personnelView',
        personnelModel:'model/personnelModel',
    },
    shim: {
    	   'bootstrap' : { 
		      "deps" :['jquery'] 
		    },
    	   'underscore': {
                exports: '_'
            },
            'jquery': {
                exports: '$'
            },  
             'httphelp' : { 
		      "deps" :['jquery','../../js/jquery.md5'] 
		    },
            'backbone': {
                deps: ['underscore', 'jquery'],
                exports: 'Backbone'
            },
            
            'validation':{
            	deps: ['backbone']          	
            },            
            'backbone.paginator':{
            	deps: ['backbone']
            },
            'backbone.mypaginator':{
            	deps: ['backbone']
            },
			'backgrid': {
			    exports: "Backgrid",
			    deps: ['underscore', 'backbone']//,//, 'backbone-pageable'
//			    init: function(_, Backbone, PageableCollection) {
//			        this.Backbone.PageableCollection = PageableCollection;
//			    }
			},
			'backgrid-button-cell':{
            	deps: ['underscore','backgrid']
            },
			'backgrid-paginator': {
			  	deps: ['underscore', 'backbone', 'backgrid']
			}//,
			/*'backgrid-select-all' : {
			  	deps: ['underscore', 'backbone', 'backgrid']
			}*/
           
    }
});

require([
    'jquery',
    'backbone',
    'router',
    'urlParse',
    'UrlConfig',
    'indexView',
    'initData',
    'httphelp'
], function ($,Backbone,Router,UrlParse,urlConfig,IndexView,InitData,httphelp) {
	
	 InitData;
	 
	 $.httphelp.token=sessionStorage.getItem('token');
	 	
	 rootView = new IndexView();
     rootView .render();
     
     var router = new Router();
	 Backbone.history.start();
});

/*接口返回扩展*/
require([
	'jquery',
    'underscore',
    'backbone',
    'localStorage',
    'supplierModel',
    'backboneQuery',
    'backbone.paginator'
    ,'../index/service/supplier.js'
],function(
	$,
	_,
	Backbone,
	localStorage,
	SupplierM,
	backboneQuery,
	backbonePaginator,
	Supplier
){
	/*接口返回错误回调函数*/
	var wrapError = function(model, options) {
		var error = options.error;
		options.error = function(resp) {
	    	if (error) error(model, resp, options);
	    	model.trigger('error', model, resp, options);
	    };
	};
	
	var ajaxHandler=
	{
		ajaxSuccess:function(resp){
			$.httphelp.authError(resp);
		},
		
		ajaxError:function(resp){
			$.httphelp.error(resp);
		},
		
		getOptions:function(httpMethod,url,callback,content){
			
			var _this=this;
			
			var options={
				cache:false,
				type:httpMethod,
				url:url,
				data:content,
				processData:true,
				headers:{
					'Authorization':$.httphelp.GetHeaderStr(httpMethod,url,content)
				},
				success:function(model,resp){	
					if(callback && callback.success){
				    	callback.success.apply(callback,arguments);
				    }else{
				    	_this.ajaxSuccess(resp);
				    }
				},
				error:function(model,resp){
				    if(callback && callback.error){
				    	callback.error.apply(callback,arguments);
				    }else{
				    	if(httpMethod.toLowerCase()!='get') resp=model;
				    	_this.ajaxError(resp);
				    }
				}
			};
			
			return options;
		}
	};
	
	/*扩展AJAX调用成功失败方法*/
	_.extend(Backbone.Model.prototype,ajaxHandler);
	_.extend(Backbone.PageableCollection.prototype,ajaxHandler);
	
	
	/*MODEL扩展*/
	_.extend(Backbone.Model.prototype,{
			
		/*获取*/
		fetchSrv:function(options){
		  options = options ? _.clone(options) : {};
	      if (options.parse === void 0) options.parse = true;
	      var model = this;
	      var success = options.success;
	      options.success = function(resp) {
	        if (!model.set(model.parse(resp.data, options), options)) return false;//改写返回解析
	        if (success) success(model, resp, options);
	        model.trigger('sync', model, resp, options);
	      };
	      wrapError(this, options);
	      return this.sync('read', this, options);
		},
		
		/*提交前验证*/
		preValidate:function(model,options){
			var attrs=model;
		    options = _.extend({validate: true}, options);
		    
		    if (!this._validate(attrs, options)) return false;
		    
		    return true;
		}
	});
	
	/*PageableCollection扩展*/
	_.extend(Backbone.PageableCollection.prototype,{
		
	});

	/*视图*/
	_.extend(Backbone.View.prototype,{
		
		viewName:'',
		
		subViews:{},
		
		getSubView:function(viewName){		
			
			var subViews = this.subViews;
			var subView;
			
			$.each(subViews,
				function(key,val){	
					//console.log(key);
					if(key === viewName)
					{
						subView = val;
						return false;
					}
					else
					{
						subView = val.getSubView(viewName);
					}
				}					
			);
			
			return subView;
		},
		
		getLevelView:function(){
			var subView = this;
			
			$(arguments).each(
				function(){
					subView = subView.getSubView(this);				
				}				
			);	
			
			return subView;
		},
		
		setSubView:function(view){
			if(!this.hasOwnProperty('subViews')) //只判断自身有没有这个属性
				this.subViews = {};
			this.subViews[view.viewName]=view;
		}
		
	});

});

/*原型测试开关*/
1 ||
require([
	'jquery',
    'underscore',
    'backbone',
    'localStorage',
    'supplierModel',
    'backboneQuery',
    'backbone.paginator'
    ,'../index/service/supplier.js'
],function(
	$,
	_,
	Backbone,
	localStorage,
	SupplierM,
	backboneQuery,
	backbonePaginator,
	Supplier
){
	
	/*backbone.ajax请求拦截器*/
	Backbone.sync = function(method, model, options) {
		  var store = model.test.store;
		
		  var resp, errorMessage;
		  //If $ is having Deferred - use it.
		  var syncDfd = Backbone.$ ?
		    (Backbone.$.Deferred && Backbone.$.Deferred()) :
		    (Backbone.Deferred && Backbone.Deferred());
		
		  //定义成功返回数据，用于执行成功回调函数，模拟服务端回调返回
		  var respSrv;
		  
		  try {
		
		    switch (method) {
		      case "read":
		      	respSrv=window[model.test.id].get(model);
		        //resp = model.id != undefined ? store.find(model) : store.findAll();
		        break;
		      case "create":
			      if(!model.models){
			      	respSrv=window[model.test.id].add(model);
			      }else{//如果为集合，则循环添加
			      	$.each(model.models,function(i,value){
			      		respSrv=window[model.test.id].add(value);
			      	});
			      }
		        //resp = store.create(model);
		        break;
		      case "update":
		      	respSrv=window[model.test.id].update(model);
		        //resp = store.update(model);
		        break;
		      case "delete":
		      	if(!model.models){
			      	respSrv=window[model.test.id].delete(model);
			      }else{//如果为集合，则删除全部
			      	respSrv=window[model.test.id].deleteAll(model);
			      }
		        //resp = store.destroy(model);
		        break;
		    }
		
		  } catch(error) {		  	
		    if (error.code === 22 && store._storageSize() === 0)
		      errorMessage = "Private browsing is unsupported";
		    else
		      errorMessage = error.message;
		  }
		
		  if (respSrv) {
		    if (options && options.success) {
		      if (Backbone.VERSION === "0.9.10") {
		        options.success(model, respSrv, options);
		      } else {
		        options.success(respSrv);
		      }
		    }
		    if (syncDfd) {
		      syncDfd.resolve(respSrv);
		    }
		
		  } else {
		    errorMessage = errorMessage ? errorMessage
		                                : "Record Not Found";
		
		    if (options && options.error)
		      if (Backbone.VERSION === "0.9.10") {
		        options.error(model, errorMessage, options);
		      } else {
		        options.error(errorMessage);
		      }
		
		    if (syncDfd)
		      syncDfd.reject(errorMessage);
		  }
		
		  // add compatibility with $.ajax
		  // always execute callback for success and error
		  if (options && options.complete) options.complete(respSrv);
		
		  return syncDfd && syncDfd.promise();
		};
	
	/*分页*/
	_.extend(Backbone.PageableCollection.prototype,  {
		fetch:function(options){
			var _this=this;
			
			var test=_this.test;
			!test || window[test.id].getPageableData(_this,function(resp){
								
				_this.parse(resp);
				_this.reset(resp.data.Items);
			});
			
		}
	
	});

});